/**
 * @file shake: 防抖动
 */
import {isThenable} from "./utils";

type Fn = () => Promise<any>

export function extendsPromiseShake () {
    // @ts-ignore
    Promise.shake = function(fn: Fn) {
        if (!fn) {
            return () => {
                return Promise.reject('params can not be empty');
            }
        }

        if (typeof fn !== 'function') {
            return () => {
                return Promise.reject('params must be function');
            }
        }

        let cache: any = null;
        return (...rest: any) => {
            if (cache) {
                return cache
            } else {
                return cache = new Promise((resolve, reject) => {
                    const promise = fn.apply(this, rest);
                    if (isThenable(promise)) {
                        promise.then((data: any) => {
                            cache = null;
                            resolve(data);
                        }).catch((error: any) => {
                            cache = null;
                            reject(error);
                        });
                    } else {
                        cache = null;
                        reject('params is not promise or thenable');
                    }
                });
            }
        }
    }
}